package org.carl.component.dingtalk.robot.model.markdown;

import com.alibaba.fastjson.JSON;
import org.carl.component.dingtalk.robot.model.At;
import org.carl.component.dingtalk.robot.model.MsgModel;

import java.util.List;
import java.util.Map;

/**
 * markdown消息构造器
 * @author hecs
 * @version $: MarkdownMessageBuilder.java v1.0 2021年11月1日 19:57:01 hecs Exp $
 * @name MarkdownMessageBuilder
 */
public class MarkdownMessageBuilder {

    /**
     * markdown消息引用符
     */
    private static final String CONTENT_QUOTE = "> ";

    /**
     * markdown消息换行符
     */
    private static final String CONTENT_NEWLINE = "     \r";

    /**
     * markdown消息加粗符
     */
    private static final String CONTENT_BOLD = "**%s**";

    /**
     * 标题格式
     */
    private static final String TITLE_PREFIX = "## ";


    private String title;

    private StringBuilder contentBuilder = new StringBuilder();

    /**
     * @所有人时:true,否则为:false
     */
    private Boolean isAtAll = Boolean.TRUE;

    /**
     * 被@人的手机号
     * @return
     */
    private List<String> atMobiles;

    public static String bold(String text) {
        return String.format(CONTENT_BOLD, text);
    }

    public static MarkdownMessageBuilder newBuilder() {
        return new MarkdownMessageBuilder();
    }


    public MarkdownMessageBuilder setTitle(String title) {
        this.title = title;
        return this;
    }

    public MarkdownMessageBuilder setIsAtAll(Boolean isAtAll) {
        this.isAtAll = isAtAll;
        return this;
    }

    public MarkdownMessageBuilder setAtMobiles(List<String> atMobiles) {
        this.atMobiles = atMobiles;
        return this;
    }

    public MarkdownMessageBuilder appendContent(Map<String, Object> infoMap) {
        if (infoMap.isEmpty()) {
            return this;
        }
        infoMap.forEach((k, v) -> this.appendContentln(bold(k) + ": " + JSON.toJSONString(v)));
        return this;
    }

    public MarkdownMessageBuilder appendContent(String content) {
        contentBuilder.append(CONTENT_QUOTE).append(content);
        return this;
    }

    public MarkdownMessageBuilder appendContentln(String line) {
        contentBuilder.append(CONTENT_QUOTE).append(line).append(CONTENT_NEWLINE);
        return this;
    }

    public MsgModel build() {
        MarkdownModel markdownModel = new MarkdownModel("Notify-" + title,CONTENT_QUOTE + TITLE_PREFIX + title + CONTENT_NEWLINE + contentBuilder.toString());
        //钉钉默认过滤词
        At at = new At();
        at.setIsAtAll(isAtAll);
        at.setAtMobiles(atMobiles);
        return MarkdownMsgModel.markdownAndAt(markdownModel, at);
    }
}
